package cn.fl.product.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysCdMapApiService;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.product.service.IMfrInfoService;
import cn.fl.product.service.ISplCrLimService;
import cn.fl.product.transform.PrjSplCrLimVOTransform;
import cn.fl.product.transform.SplCrLimVOTransform;
import cn.fl.product.transform.SplInfoVOTransform;
import cn.fl.product.vo.PrjSplCrLimVO;
import cn.fl.product.vo.SplCrLimVO;
import cn.fl.project.condition.PrjPrdBscInfoQueryCondition;
import cn.fl.project.condition.PrjSplCrLimQueryCondition;
import cn.fl.project.constant.PrjSplCrLimConstant;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.dto.PrjPrdBscInfoDTO;
import cn.fl.project.dto.PrjSplCrLimDTO;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.service.IPrjSplCrLimApiService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.transform.PrjPrdBscInfoVOTransform;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.service.ISysUsrService;
import fl.spl.facade.spl.api.ISplCrLimApiService;
import fl.spl.facade.spl.api.ISplInfoApiService;
import fl.spl.facade.spl.condition.SplCrLimQueryCondition;
import fl.spl.facade.spl.condition.SplInfoQueryCondition;
import fl.spl.facade.spl.constant.SplCrLimConstant;
import fl.spl.facade.spl.dto.SplCrLimDTO;
import fl.spl.facade.spl.dto.SplInfoDTO;

/**
 * @Description: 供应商信息表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class SplCrLimServiceImpl implements ISplCrLimService {

	/**
	 * 供应商 API 暴露服务
	 */
	@Autowired
	private ISplCrLimApiService splCrLimApiService;
	/**
	 * 项目授信 服务
	 */
	@Autowired
	private IPrjSplCrLimApiService prjSplCrLimApiService;
	
	/**
	 * 映射表API服务
	 */
	@Autowired
	private ISysCdMapApiService sysCdMapApiService;
	
	/**
	 * 组织架构API暴露服务
	 */
	@Autowired
	private ISysOrgApiService sysOrgApiService;
	
	@Autowired
	private IMfrInfoService prdMfrInfoService;
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IProjectApiService projectApiService;
	
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 本地用户服务
	 */
	@Autowired
	private ISysUsrService sysUsrService;
	
	@Autowired
	private IPrjPrdPaySchMService prjPrdPaySchMService;
	@Autowired
	private ISplInfoApiService splInfoApiService;
	

	@Override
	public Long add(SplCrLimDTO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.newWebLogger("新增供应商授信失败,供应商授信对象参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			throw new BaseException(BaseExceptionConstant.COMMON_0001,BaseExceptionConstant.COMMON_0001_NAME);
		}
		Long s = this.splCrLimApiService.addSplCrLim(entity,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		return s;
	}
	
	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	private List<KeyValueVO> getKvList(String grpCd){
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.warn(LogExceptionEnum.COMMON_CODE_0001);

		} catch (Exception e) {
			BaseLogUtils.newWebLogger("获取字典项组失败,系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
					.setWarning(false)
					.setThrowable(e)
					.error(LogExceptionEnum.COMMON_CODE_0099);

		}
		return kvList;
	}
	
	/**
	 * 设置页面字符串数据
	 * @param list
	 * @return
	 */
	private String getString(List<?> list){
		StringBuilder sb = new StringBuilder();  
	    if (CollectionUtils.isNotEmpty(list)) {  
	        for (int i = 0; i < list.size(); i++) {  
	            if (i < list.size() - 1) {  
	                sb.append(list.get(i) + ";");  
	            } else {  
	                sb.append(list.get(i));  
	            }  
	        }  
	    }
		return sb.toString();
	}

	@Override
	public List<KeyValueVO> searchBuOrgCdList() throws BaseException {
		List<SysOrgDTO> dtoList = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getFlServiceSysCd());
		List<KeyValueVO> kvList = new ArrayList<KeyValueVO>();
		if(CollectionUtils.isNotEmpty(dtoList)){
			for (SysOrgDTO dto : dtoList) {
				KeyValueVO kv = new KeyValueVO();
				kv.setKey(dto.getOrgCd());
				kv.setValue(dto.getOrgDispNm());
				kvList.add(kv);
			}
		}
		return kvList;
	}
	@Override
	public List<KeyValueVO> searchCrTypCdList() throws BaseException {
		return this.getKvList(SplCrLimConstant.CODE_GRP_CR_TYP_CD);
	}
	/**
     * 根据条件查询所有
     * @param condition
     * @return
     */
	@Override
    public List<SplCrLimVO> searchList(SplCrLimQueryCondition condition) throws BaseException{
    	if(null == condition){
    		condition=new SplCrLimQueryCondition();
		}
		List<SplCrLimDTO> listDTO=this.splCrLimApiService.searchSplCrLimList(condition);
		List<SplCrLimVO> listVO = new ArrayList<SplCrLimVO>();
		if(CollectionUtils.isNotEmpty(listDTO)){
            List<SplCrLimVO> voList=SplCrLimVOTransform.toVOList(listDTO);
            this.setDictData(voList);
            listVO = this.doBuOrgCd(voList);
        }
        return listVO;
    }
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<SplCrLimVO> voList){
		if(CollectionUtils.isEmpty(voList)){
			return;
		}
		//Map<String, String> _CdMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, SplCrLimConstant.CODE_CD);
		for(SplCrLimVO vo:voList){
//			if (_CdMap != null && _CdMap.containsKey(vo.getCd())) {
//            	vo.setCdNm(_CdMap.get(vo.getCd()));
//        	}	
			PrjSplCrLimQueryCondition qc = new PrjSplCrLimQueryCondition();
			qc.setLimId(vo.getId());
			PrjSplCrLimDTO dto = this.prjSplCrLimApiService.getSumLimAmt(qc);
			Double sumOp = DecimalUtils.convertFenToYuan(dto.getSumLimOpAmt());
			Double sumRb = DecimalUtils.convertFenToYuan(dto.getSumLimRbAmt());
			Double crAmtD = DecimalUtils.convertFenToYuan(vo.getCrAmt());
			vo.setSumLimOpAmt(sumOp);
			vo.setSumLimRbAmt(sumRb);
			vo.setCrAmtD(crAmtD);
			Double restCrAmt = 0d;
			if("1".equals(vo.getCrTypCd()+"")){
				restCrAmt = crAmtD - sumOp + sumRb;
			}else{
				restCrAmt = crAmtD - sumOp;
			}
			vo.setRestCrAmt(restCrAmt);
		}
	}
	/**
     * 添加数据字典名称
     * @param voList
     */
	public void setPrjSplDictData(List<PrjSplCrLimVO> voList){
		if(CollectionUtils.isEmpty(voList)){
			return;
		}
		Map<String, String> limTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), PrjSplCrLimConstant.CODE_GRP_LIM_TYP_CD);
		for(PrjSplCrLimVO vo:voList){
			if (limTypCdMap != null && limTypCdMap.containsKey(vo.getLimTypCd())) {
            	vo.setLimTypCdNm(limTypCdMap.get(vo.getLimTypCd()));
        	}	
			PrjPrdPaySchMVO payVO = this.prjPrdPaySchMService.selectById(vo.getPaySchId());
			vo.setPaySchNo(payVO.getPaySchNo());
		}
	}
	@Override
	public Pager serchPrjListPage(Pager page) throws BaseException{
		PrjSplCrLimQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new PrjSplCrLimQueryCondition());
        }
		condition=(PrjSplCrLimQueryCondition)page.getCondition();
//        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
//        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
//        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		//page=this.splCrLimApiService.searchSplCrLimListPage(page);
		page = this.prjSplCrLimApiService.searchPrjSplCrLimListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<PrjSplCrLimVO> voList=PrjSplCrLimVOTransform.toVOList((List<PrjSplCrLimDTO>)page.getResultList());
            this.setPrjSplDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        SplCrLimQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new SplCrLimQueryCondition());
        }
		condition=(SplCrLimQueryCondition)page.getCondition();
//        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
//        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
//        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.splCrLimApiService.searchSplCrLimListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<SplCrLimVO> voList=SplCrLimVOTransform.toVOList((List<SplCrLimDTO>)page.getResultList());
            this.setDictData(voList);
            List<SplCrLimVO> voBuList = this.doBuOrgCd(voList);
            page.setResultList(voBuList);
        }
        return page;
	}
	//事业部处理
	public List<SplCrLimVO> doBuOrgCd(List<SplCrLimVO> listSplVo) throws BaseException{
		List<SplCrLimVO> listVo = new ArrayList<SplCrLimVO>();
		String orgCd = CurrentThreadContext.getCurrentBuOrgCd();
		for(int i =0 ;i < listSplVo.size(); i++){
			String splBuOrgCd = listSplVo.get(i).getOrgCd();
			if(StringUtils.isNotEmpty(splBuOrgCd) && splBuOrgCd.startsWith(orgCd)){
				listVo.add(listSplVo.get(i));
			}
		}
		return listVo;
	}
	@Override
	public Pager serchPrjSplPrdListPage(Pager page) throws BaseException{
		PrjPrdBscInfoQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new PrjPrdBscInfoQueryCondition());
        }
		page = this.projectApiService.searchPrjPrdBscListPage(page,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		if(CollectionUtils.isNotEmpty(page.getResultList())){
			List<PrjPrdBscInfoDTO> prjPrdList = (List<PrjPrdBscInfoDTO>)page.getResultList();
			List<Long> splIdList = new ArrayList<Long>();
			for (PrjPrdBscInfoDTO prjPrdBscInfoDTO : prjPrdList) {
				if(null!=prjPrdBscInfoDTO.getSplId()){
					splIdList.add(prjPrdBscInfoDTO.getSplId());
				}
			}
			SplInfoQueryCondition splQc  = new SplInfoQueryCondition();
			splQc.setIds(splIdList);
			List<SplInfoDTO> splList = this.splInfoApiService.searchSplInfoList(splQc,CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			List<PrjPrdBscInfoVO> list = PrjPrdBscInfoVOTransform.toVOList(prjPrdList);
			
			if(CollectionUtils.isNotEmpty(list)&&CollectionUtils.isNotEmpty(splList)){
				for (PrjPrdBscInfoVO prjPrdBsc : list) {
					for (SplInfoDTO spl : splList) {
						if(null!=prjPrdBsc.getSplId()&&prjPrdBsc.getSplId().equals(spl.getId())){
							prjPrdBsc.setSplInfoVO(SplInfoVOTransform.toVO(spl));
						}
					}
				}
			}
			if(CollectionUtils.isNotEmpty(list)){
				for (PrjPrdBscInfoVO prjPrdBsc : list) {
					if(StringUtils.isNotEmpty(""+prjPrdBsc.getSplId()) && StringUtils.isNotEmpty(""+prjPrdBsc.getPrjId())){
						PrjBscInfoDTO prjBscInfoDTO = this.projectApiService.selectPrjBscInfoById(prjPrdBsc.getPrjId(),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
						if(StringUtils.isNotBlank(prjBscInfoDTO.getBuOrgCd())){
							PrjSplCrLimQueryCondition prjSplCrLimQueryCondition = new PrjSplCrLimQueryCondition();
							prjSplCrLimQueryCondition.setSplId(prjPrdBsc.getSplId());
							prjSplCrLimQueryCondition.setOrgCd(prjBscInfoDTO.getBuOrgCd());
							PrjSplCrLimDTO prjSplCrLimDTO = this.prjSplCrLimApiService.getPrjSplCrByQc(prjSplCrLimQueryCondition);
							//prjPrdBsc.setCrAmtD(crAmtD);
							Double sumOp = DecimalUtils.convertFenToYuan(prjSplCrLimDTO.getSumLimOpAmt());
							Double sumRb = DecimalUtils.convertFenToYuan(prjSplCrLimDTO.getSumLimRbAmt());
							Double crAmtD = DecimalUtils.convertFenToYuan(prjSplCrLimDTO.getCrAmt());
							prjPrdBsc.setCrAmtD(crAmtD);
							Double restCrAmt = 0d;
							if("1".equals(prjSplCrLimDTO.getCrTypCd()+"")){
								restCrAmt = crAmtD - sumOp + sumRb;
							}else{
								restCrAmt = crAmtD - sumOp;
							}
							prjPrdBsc.setRestCrAmt(restCrAmt);
						}
					}
				}
			}
			page.setResultList(list);
		}
        return page;
	}
	
}
